const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const colors = require('colors');
/**
 * 获取所有满足需求的文件
 * @param dir
 * @returns {Array}
 */
const getAllFiles = (dir) => {
  if (!fs.existsSync(dir)) {
    console.log(`${colors.red('➤')} ${colors.red(`国际化文件夹${dir}不存在`)}`);
    process.exit(0);
  } else {
    let results = [];
    fs.readdirSync(dir).forEach((item) => {
      item = path.join(dir, item);
      if (fs.lstatSync(item).isDirectory()) {
        results.push(...getAllFiles(item));
      } else {
        // 设置国际化需要处理的文件
        const supportLang = ['.vue', '.js', '.ts'];
        const reg = new RegExp(`.*(${supportLang.join('|')}$)`);
        // 以min结尾的文件不处理（min.js min.ts min.vue ）
        const minReg = new RegExp(
          `.*(${supportLang.map((text) => `.min${text}`).join('|')}$)`
        );
        if (reg.test(item) && !minReg.test(item)) results.push(item);
      }
    });
    return results;
  }
};

//创建多层文件夹 异步
const mkdirs = function (dirpath, mode = () => {}, callback) {
  fs.exists(dirpath, function (exists) {
    if (exists) {
      callback(dirpath);
    } else {
      mkdirs(path.dirname(dirpath), mode, function () {
        fs.mkdir(dirpath, mode, callback);
      });
    }
  });
};

//创建多层文件夹 同步
function mkdirsSync(dirname, mode) {
  if (fs.existsSync(dirname)) {
    return true;
  } else {
    if (mkdirsSync(path.dirname(dirname), mode)) {
      fs.mkdirSync(dirname, mode);
      return true;
    }
  }
}
exports.Md5 = function (str) {
  return crypto.createHash('md5').update(str).digest('hex');
};

/**
 * 获取16位的MD5值
 * @param str
 * @return {string}
 * @constructor
 */
exports.Md5_16 = function (str) {
  return exports.Md5(str).slice(8, 24);
};
exports.getAllFiles = getAllFiles;
exports.mkdirs = mkdirs;
exports.mkdirsSync = mkdirsSync;
